#coding:utf-8
from urllib import urlopen
from lovewith.settings import SITE_URL
from lovewith.api.qq.qq import APIClient


class QQ:
    def __init__(self):
        # app key
        client_id = '100307429'
        # app secret
        client_secret = 'c6a6f04ca2aee956464ff868613f3556'
        # callback url
        redirect_uri = '%su/auth/qq/' % SITE_URL

        self.client = APIClient(client_id, client_secret, redirect_uri)

    #获取openid
    def get_open_id(self):
        return self.client.get_openid()

    #获取登录url
    def get_login_server(self):
        return self.client.get_authorization_url('authorize', scopes=['get_info', 'add_t', 'add_pic_t', 'add_idol'])

    #获取授权token
    def get_token(self, code):
        return self.client.request_access_token(code)

    #保存token
    def save_token(self, token, expires):
        self.client.set_access_token(token, expires)

    #获取腾讯微博用户信息
    def get_tencent_wb_user_info(self):
        try:
            user_data = self.client.get.user__get_info()
            return user_data
        except StandardError, api_error:
            return None

    #获取腾讯QQ信息
    def get_qzone_info(self):
        try:
            user_data = self.client.get.user__get_user_info()
            return user_data
        except StandardError, api_error:
            return None

    #关注用户
    def follow(self, name):
        try:
            user_data = self.client.get.relation__add_idol(name)
        except StandardError, api_error:
            pass

    #发送文字微博
    def post_text(self, text):
        try:
            user_data = self.client.post.t__add_t(content=text)
        except StandardError, api_error:
            pass

    #发送图文微博
    def post_with_pic(self, text, pic):
        if pic.find('http') < 0:
            pic_handle = open(pic, 'rb')
        else:
            pic_handle = urlopen(pic)
        try:
            self.client.post.t__add_pic_t(content=text, pic=pic_handle)
        except StandardError, api_error:
            pass